﻿using Microsoft.Practices.Prism.Modularity;
using Microsoft.Practices.ServiceLocation;
using Microsoft.Practices.Unity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using Microsoft.Practices.Prism.Logging;
using System.Xml.Linq;

namespace RedisMonitor
{
    public class RedisBootstrapper : Microsoft.Practices.Prism.UnityExtensions.UnityBootstrapper
    {
        protected override DependencyObject CreateShell()
        {
            return ServiceLocator.Current.GetInstance<Shell>();
        }

        protected override void InitializeShell()
        {
            base.InitializeShell();

           
            Application.Current.MainWindow = (Window)this.Shell;
            Application.Current.MainWindow.Show();
        }


        protected override void ConfigureModuleCatalog()
        {
            base.ConfigureModuleCatalog();

            ModuleCatalog moduleCatalog = (ModuleCatalog)this.ModuleCatalog;

            moduleCatalog.AddModule(typeof(RedisModule.RedisModule));
        }


        protected override void ConfigureContainer()
        {
            base.ConfigureContainer();
            RedisDomain.ModuleUtils.Init(Resolve, RegisterType, RegisterSingleType, RegisterInstance);
            ViewModels.SettingsAppearanceVm vm = new ViewModels.SettingsAppearanceVm(GetAppConfigPath());

            RegisterInstance(typeof(ViewModels.SettingsAppearanceVm), vm);
        }

        public static string GetAppConfigPath()
        {
            var directory = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config");

            var p = System.IO.Path.Combine(directory, "app.config");

            if (!System.IO.File.Exists(p))
            {
                if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(p)))
                {
                    System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(p));
                }


                var element = new XElement("ApplicationSettings");
                element.Save(p);
            }

            return p;
        }

        protected override ILoggerFacade CreateLogger()
        {
            return RedisDomain. Logger.Instance;
        }

        public object Resolve(Type type)
        {
            return Container.Resolve(type);
        }

        public void RegisterType(Type from ,Type to)
        {
            Container.RegisterType(from ,to);
        }

        public void RegisterInstance(Type type,object instance)
        {
            Container.RegisterInstance(type, instance);
        }

        public  void RegisterSingleType(Type type)
        {
            Container.RegisterType(type);
        }
    }
    
}
